package pers.lan.print.itext;

import com.itextpdf.barcodes.Barcode39;
import com.itextpdf.barcodes.BarcodeQRCode;
import com.itextpdf.barcodes.qrcode.EncodeHintType;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.borders.DoubleBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import pers.lan.print.Printer;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * chapter1
 *
 * @author <a href="mailto:1728209643@qq.com">lan</a>
 * @class pers.lan.print.itext.Chapter1
 * @date 2019-04-10 14:45
 */
@SuppressWarnings("Duplicates")
public class Chapter1 {

    private final static String dest = "/Users/lan/Desktop/test.pdf";

    @Test
    public void test2() throws IOException {
        PdfWriter writer = new PdfWriter(dest);
        PdfDocument pdf = new PdfDocument(writer);
        Document document = new Document(pdf, PageSize.A4.rotate());

        InputStream inputStream = new FileInputStream("/Users/lan/Desktop/GB2312.ttf");
        byte[] byteArray = IOUtils.toByteArray(inputStream);
        PdfFont font = PdfFontFactory.createFont(byteArray, PdfEncodings.IDENTITY_H, false);


        Table table = new Table(new float[]{3, 1, 3});
        table.setWidth(UnitValue.createPercentValue(100));
        table.setFontSize(10f);
        table.setTextAlignment(TextAlignment.CENTER);
        table.setBorder(Border.NO_BORDER);
        table.addCell(
                new Cell()
                        .add(
                                new Paragraph("第一个xxx")
                                        .setFont(font)
                        )
                        .setBorder(Border.NO_BORDER)
        );
        table.addCell(
                new Cell()
                        .add(
                                new Paragraph("")
                                        .setFont(font)
                        )
                        .setBorder(Border.NO_BORDER)
        );
        table.addCell(
                new Cell()
                        .add(
                                new Paragraph("第3个xxx")
                                        .setFont(font)
                        )
                        .setBorder(Border.NO_BORDER)
        );


        document.add(table);


        BarcodeQRCode qrCode = new BarcodeQRCode();
        qrCode.setCode("lalala啦啦啦");
        Map<EncodeHintType, Object> map = new HashMap<EncodeHintType, Object>();
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        qrCode.setHints(map);
        Image image = new Image(qrCode.createFormXObject(pdf));
        image.setWidth(100);
        document.add(image);

        document.close();


//        print(dest, new HashMap<Object, Object>());
    }

    @Test
    public void test3() throws IOException {
        PdfWriter writer = new PdfWriter(dest);
        PdfDocument pdf = new PdfDocument(writer);
//        float[] margins = new float[]{px(0f), px(0.6f), px(0.65f), px(0.6f)};
        float[] margins = new float[]{px(0.8f), px(0.6f), px(0.65f), px(0.6f)};
        float horizontalMargin = px(0.2f);
        float verticalMargin = px(0f);
        float width = px(4.8f);
        float height = px(3f);
        PageSize pageSize = PageSize.A4;
        Document document = get(pdf, margins, horizontalMargin, verticalMargin, width, height, 4, 9, pageSize);
        document.close();

        Printer.print(dest, new HashMap<>());
    }

    /**
     * 把厘米转成像素,先转成英寸1cm = 0.3937008in,每英寸72像素
     *
     * @param cm 厘米
     * @return 像素
     */
    private float px(float cm) {
        return cm * 0.3937008f * 72f;
    }

    /**
     * @param pdf              pdfDocument
     * @param margins          top right bottom left
     * @param horizontalMargin cell的水平间隔
     * @param verticalMargin   cell的竖直间隔
     * @param width            cell的宽
     * @param height           cell的高度
     * @param horizontalN      水平方向每行cell个数
     * @param verticalN        竖直方向每列cell个数
     * @param pageSize         纸张大小
     * @return document
     */
    private Document get(PdfDocument pdf, float[] margins, float horizontalMargin, float verticalMargin, float width, float height, int horizontalN, int verticalN, PageSize pageSize) throws IOException {
        Document document = new Document(pdf, pageSize);
        InputStream inputStream = new FileInputStream("/Users/lan/Desktop/GB2312.ttf");
        byte[] byteArray = IOUtils.toByteArray(inputStream);
        PdfFont font = PdfFontFactory.createFont(byteArray, PdfEncodings.IDENTITY_H, false);

        document.setTopMargin(margins[0]);
        document.setRightMargin(margins[1]);
        document.setLeftMargin(margins[3]);

        document.setBorder(new DoubleBorder(ColorConstants.BLACK, 3));

        float[] tableWidths = new float[horizontalN * 2 - 1];
        for (int i = 0; i < horizontalN * 2 - 1; i++) {
            tableWidths[i] = i % 2 == 0 ? width : horizontalMargin;
        }
        Table table = new Table(tableWidths);
        table.setMargin(0f);

        for (int i = 0; i < verticalN; i++) {
            for (int j = 0; j < horizontalN * 2 - 1; j++) {
                Cell cell;

                if (j % 2 == 0) {
                    cell = new Cell()
                            .add(
                                    getQrImg(System.currentTimeMillis() + "哈斯噶阿四大", height - 10, pdf)
//                                    getBarcode39(System.currentTimeMillis() + "", width, height - 10, pdf, font)
                                            .setHorizontalAlignment(HorizontalAlignment.CENTER)
                            )
                            .setWidth(width)
                            .setHeight(height - 5);
                } else {
                    cell = new Cell().setWidth(horizontalMargin);
                }
//                cell.setBorder(Border.NO_BORDER);


                table.addCell(cell);
            }
            if (verticalMargin != 0f) {
                for (int j = 0; j < horizontalN * 2 - 1; j++) {
                    table.addCell(
                            new Cell()
//                                    .setBorder(Border.NO_BORDER)
                                    .setHeight(verticalMargin)
                    );
                }
            }
        }
        document.add(table);


        return document;
    }

    private Image getQrImg(String code, float width, PdfDocument pdf) {
        BarcodeQRCode qrCode = new BarcodeQRCode();
        qrCode.setCode(code);
        Map<EncodeHintType, Object> map = new HashMap<EncodeHintType, Object>();
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");

        qrCode.setHints(map);
        Image image = new Image(qrCode.createFormXObject(pdf));
        image.setWidth(width);
        return image;
    }

    private Image getBarcode39(String code, float width, float height, PdfDocument pdf, PdfFont font) {
        Barcode39 barcode39 = new Barcode39(pdf);
        barcode39.setCode(code);
        barcode39.setAltText("我是条形码");
        barcode39.setFont(font);
        return new Image(barcode39.createFormXObject(pdf)).setWidth(width).setHeight(height);
    }


    @Test
    public void test1() throws IOException {
        PdfWriter writer = new PdfWriter(dest);
        PdfDocument pdf = new PdfDocument(writer);
        Document document = new Document(pdf, PageSize.A4.rotate());
        document.setMargins(20, 20, 20, 20);

        InputStream inputStream = new FileInputStream("/Users/lan/Desktop/GB2312.ttf");
        byte[] byteArray = IOUtils.toByteArray(inputStream);
        PdfFont font = PdfFontFactory.createFont(byteArray, PdfEncodings.IDENTITY_H, false);
        PdfFont bold = PdfFontFactory.createFont(byteArray, PdfEncodings.IDENTITY_H, false);

        Table table = new Table(new float[]{4, 1, 3, 4, 3, 3, 3, 3, 1});
        table.setWidth(UnitValue.createPercentValue(100));
        BufferedReader br = new BufferedReader(new FileReader("/Users/lan/Desktop/data.csv"));
        String line = br.readLine();
        process(table, line, bold, true);
        while ((line = br.readLine()) != null) {
            process(table, line, font, false);
        }
        br.close();
        document.add(table);
        document.close();
    }

    private void process(Table table, String line, PdfFont font, boolean isHeader) {
        StringTokenizer tokenizer = new StringTokenizer(line, ";");
        while (tokenizer.hasMoreTokens()) {
            if (isHeader) {
                table.addHeaderCell(
                        new Cell().add(
                                new Paragraph(tokenizer.nextToken()).setFont(font)));
            } else {
                table.addCell(
                        new Cell().add(
                                new Paragraph(tokenizer.nextToken()).setFont(font)).setFontSize(10));
            }
        }
    }


}
